package cn.jeeweb.modules.web.labor.controller;

import cn.jeeweb.core.common.data.DuplicateValid;
import cn.jeeweb.core.model.AjaxJson;
import cn.jeeweb.core.model.PageJson;
import cn.jeeweb.core.model.ValidJson;
import cn.jeeweb.core.query.annotation.PageableDefaults;
import cn.jeeweb.core.query.data.PropertyPreFilterable;
import cn.jeeweb.core.query.data.Queryable;
import cn.jeeweb.core.query.utils.QueryableConvertUtils;
import cn.jeeweb.core.query.wrapper.EntityWrapper;
import cn.jeeweb.core.security.shiro.authz.annotation.RequiresMethodPermissions;
import cn.jeeweb.core.utils.MessageUtils;
import cn.jeeweb.core.utils.ObjectUtils;
import cn.jeeweb.core.utils.StringUtils;
import cn.jeeweb.modules.common.Global;
import cn.jeeweb.modules.sys.utils.UserUtils;
import cn.jeeweb.modules.web.civil.entity.HuCivilMsg;
import cn.jeeweb.modules.web.civil.service.IHuCivilMsgService;
import cn.jeeweb.modules.web.expertise.entity.HuExpertiseMsg;
import cn.jeeweb.modules.web.expertise.service.IHuExpertiseMsgService;
import cn.jeeweb.modules.web.human.entity.HuHumanMsg;
import cn.jeeweb.modules.web.human.entity.HuVeterans;
import cn.jeeweb.modules.web.human.entity.HumanRecruit;
import cn.jeeweb.modules.web.human.service.IHuHumanMsgService;
import cn.jeeweb.modules.web.human.service.IHuVeteransService;
import cn.jeeweb.modules.web.human.service.IHumanRecruitService;
import cn.jeeweb.core.utils.upload.exception.FileNameLengthLimitExceededException;
import cn.jeeweb.core.utils.upload.exception.InvalidExtensionException;
import cn.jeeweb.modules.sys.entity.Attachment;
import cn.jeeweb.modules.sys.service.IAttachmentService;
import cn.jeeweb.modules.sys.utils.UserUtils;
import cn.jeeweb.modules.web.labor.content.HuLaborContent;
import cn.jeeweb.modules.web.labor.entity.HuEmployMent;
import cn.jeeweb.modules.web.labor.entity.HuLabor;
import cn.jeeweb.modules.web.labor.entity.HuEmployMent;
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.serializer.SerializeFilter;
import org.apache.commons.fileupload.FileUploadBase;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.validation.BindingResult;
import org.springframework.web.bind.annotation.*;
import cn.jeeweb.core.common.controller.BaseBeanController;
import cn.jeeweb.core.security.shiro.authz.annotation.RequiresPathPermission;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.validation.Valid;
import java.io.File;
import java.io.IOException;
import java.sql.Timestamp;
import java.util.Iterator;
import java.util.List;

import cn.jeeweb.modules.web.labor.service.IHuLaborService;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.multipart.MultipartHttpServletRequest;
import org.springframework.web.multipart.commons.CommonsMultipartResolver;

/**   
 * @Title: hu_labor
 * @Description: hu_labor
 * @author &Iacute;&otilde;&acute;&aelig;&frac14;&ucirc;
 * @date 2018-01-31 15:03:08
 * @version V1.0   
 *
 */
@Controller
@RequestMapping("${admin.url.prefix}/labor/hulabor")
@RequiresPathPermission("labor:hulabor")
public class HuLaborController extends BaseBeanController<HuLabor> {

    public static final String DEFAULT_IMAGE_PATH = "/resources/repository/cover/";

    @Autowired
    protected IHuLaborService huLaborService;
    @Autowired
    private IHuCivilMsgService huCivilMsgService;
    @Autowired
    private IHuExpertiseMsgService huExpertiseMsgService;
    @Autowired
    private IHuHumanMsgService huHumanMsgService;

    @Autowired
    private IAttachmentService attachmentService;
    public HuLabor get(String id) {
        if (!ObjectUtils.isNullOrEmpty(id)) {
            return huLaborService.selectById(id);
        } else {
            return newModel();
        }
    }

    @RequiresMethodPermissions("list")
    @RequestMapping(method = RequestMethod.GET)
    public String list(Model model, HttpServletRequest request, HttpServletResponse response) {
        return display("list");
    }

    @RequestMapping(value = "ajaxList", method = { RequestMethod.GET, RequestMethod.POST })
    @PageableDefaults(sort = "id=desc")
    private void ajaxList(Queryable queryable, PropertyPreFilterable propertyPreFilterable, HttpServletRequest request,
                          HttpServletResponse response) throws IOException {
        EntityWrapper<HuLaborContent> entityWrapper = new EntityWrapper<HuLaborContent>();
        propertyPreFilterable.addQueryProperty("id");
        String orgId = UserUtils.getOrg();
        EntityWrapper.otherSql = Global.otherSql(orgId);
        // 预处理
        QueryableConvertUtils.convertQueryValueToEntityValue(queryable, entityClass);
        SerializeFilter filter = propertyPreFilterable.constructFilter(entityClass);
        PageJson<HuLaborContent> pagejson = new PageJson<HuLaborContent>(huLaborService.selectAllList(queryable,entityWrapper));
        EntityWrapper.otherSql = null;
                String content = JSON.toJSONString(pagejson, filter);
        StringUtils.printJson(response, content);
    }

    @RequestMapping(value = "create", method = RequestMethod.GET)
    public String create(Model model, HttpServletRequest request, HttpServletResponse response) {
        if (!model.containsAttribute("data")) {
            model.addAttribute("data", newModel());
        }
        model.addAttribute("human", new HuHumanMsg());
        model.addAttribute("civil", new HuCivilMsg());
        model.addAttribute("exprtisemsg", new HuExpertiseMsg());
        return display("edit");
    }




    @RequestMapping(value = "create", method = RequestMethod.POST)
    @ResponseBody
    public AjaxJson create(Model model, @Valid @ModelAttribute("data") HuLabor huLabor,HuEmployMent huEmployMent,
                           @Valid @ModelAttribute("human")HuHumanMsg humanMsg, BindingResult result,
                           @Valid @ModelAttribute("civil") HuCivilMsg huCivilMsg,@Valid @ModelAttribute("exprtisemsg") HuExpertiseMsg expertiseMsg,
                           HttpServletRequest request, HttpServletResponse response) {
        return doSave(huLabor,huEmployMent,humanMsg, huCivilMsg, expertiseMsg, request, response, result);
    }

    @RequestMapping(value = "{id}/update", method = RequestMethod.GET)
    public String update(@PathVariable("id") String id, Model model, HttpServletRequest request,
                              HttpServletResponse response) {
        HuLabor huLabor = get(id);
        model.addAttribute("data", huLabor);
//        HuCivilMsg huCivilMsg = huCivilMsgService.
        model.addAttribute("human", huHumanMsgService.selectByLadorId(id));
        model.addAttribute("civil", huCivilMsgService.selectByLadorId(id));
        model.addAttribute("exprtisemsg", huExpertiseMsgService.selectByLadorId(id));
        return display("edit");
    }

    @RequestMapping(value = "{id}/update", method = RequestMethod.POST)
    @ResponseBody
    public AjaxJson update(Model model, @Valid @ModelAttribute("data") HuLabor huLabor, @Valid @ModelAttribute("human")HuHumanMsg humanMsg,
                           HuEmployMent huEmployMent, BindingResult result,
                           @Valid @ModelAttribute("civil") HuCivilMsg huCivilMsg,
                           @Valid @ModelAttribute("exprtisemsg") HuExpertiseMsg expertiseMsg,
                           HttpServletRequest request, HttpServletResponse response) {
        return doSave(huLabor, huEmployMent,humanMsg, huCivilMsg, expertiseMsg, request, response, result);
    }

    @RequestMapping(value = "/save", method = RequestMethod.POST)
    @ResponseBody
    public AjaxJson doSave(HuLabor huLabor, HuEmployMent huEmployMent, HuHumanMsg humanMsg, HuCivilMsg huCivilMsg,HuExpertiseMsg expertiseMsg,
                           HttpServletRequest request, HttpServletResponse response,
                           BindingResult result) {
        AjaxJson ajaxJson = new AjaxJson();
        huLabor.setCreateBy(UserUtils.getUser());
        huLabor.setCreateDate(new Timestamp(System.currentTimeMillis()));
        String orgId = UserUtils.getOrg();
        huLabor.setOrganizationId(orgId);
      //  huLabor.setPhoto(upload( request,response));
        ajaxJson.success("保存成功");
        if (hasError(huLabor, result)) {
            // 错误提示
            String errorMsg = errorMsg(result);
            if (!StringUtils.isEmpty(errorMsg)) {
                ajaxJson.fail(errorMsg);
            } else {
                ajaxJson.fail("保存失败");
            }
            return ajaxJson;
        }
        try {
            if (StringUtils.isEmpty(huLabor.getId())) {
                huLaborService.insertLabor(huLabor,huEmployMent, humanMsg, huCivilMsg, expertiseMsg);
               // huLaborService.insert(huLabor);
            } else {
                huLaborService.insertOrUpdate(huLabor);
            }
        } catch (Exception e) {
            e.printStackTrace();
            ajaxJson.fail("保存失败!<br />原因:" + e.getMessage());
        }
        return ajaxJson;
    }

    @RequestMapping(value = "{id}/delete", method = RequestMethod.POST)
    @ResponseBody
    public AjaxJson delete(@PathVariable("id") String id) {
        AjaxJson ajaxJson = new AjaxJson();
        ajaxJson.success("删除成功");
        try {
            huLaborService.deleteById(id);
        } catch (Exception e) {
            e.printStackTrace();
            ajaxJson.fail("删除失败");
        }
        return ajaxJson;
    }

    @RequestMapping(value = "batch/delete", method = { RequestMethod.GET, RequestMethod.POST })
    @ResponseBody
    public AjaxJson batchDelete(@RequestParam(value = "ids", required = false) String[] ids) {
        AjaxJson ajaxJson = new AjaxJson();
        ajaxJson.success("删除成功");
        try {
            List<String> idList = java.util.Arrays.asList(ids);
            huLaborService.deleteBatchIds(idList);
        } catch (Exception e) {
            e.printStackTrace();
            ajaxJson.fail("删除失败");
        }
        return ajaxJson;
    }

    @RequestMapping(value = "/{id}", method = RequestMethod.GET)
    public String view(Model model, @PathVariable("id") String id, HttpServletRequest request,
                       HttpServletResponse response) {
        HuLabor huLabor = get(id);
        model.addAttribute("data", huLabor);
        return display("edit");
    }

    @RequestMapping(value = "validate", method = { RequestMethod.GET, RequestMethod.POST })
    @ResponseBody
    public ValidJson validate(DuplicateValid duplicateValid, HttpServletRequest request) {
        ValidJson validJson = new ValidJson();
        Boolean valid = Boolean.FALSE;
        try {
            EntityWrapper<HuLabor> entityWrapper = new EntityWrapper<HuLabor>(entityClass);
            valid = huLaborService.doValid(duplicateValid,entityWrapper);
            if (valid) {
                validJson.setStatus("y");
                validJson.setInfo("验证通过!");
            } else {
                validJson.setStatus("n");
                if (!StringUtils.isEmpty(duplicateValid.getErrorMsg())) {
                    validJson.setInfo(duplicateValid.getErrorMsg());
                } else {
                    validJson.setInfo("当前信息重复!");
                }
            }
        } catch (Exception e) {
            validJson.setStatus("n");
            validJson.setInfo("验证异常，请检查字段是否正确!");
        }
        return validJson;
    }

    /******************************************************/

    /**
     * 贫困劳动力数据界面跳转
     * @param model
     * @param request
     * @param response
     * @return
     */
    //@RequiresMethodPermissions("listPoor")
    @RequestMapping(value="listPoor",method = RequestMethod.GET)
    public String listPoor(Model model, HttpServletRequest request, HttpServletResponse response) {
        return display("listPoor");
    }

    /**
     * 获取贫困劳动力数据
     */
    @RequestMapping(value="ajaxListPoor",method = RequestMethod.GET)
    public void ajaxListPoor(Queryable queryable, PropertyPreFilterable propertyPreFilterable, HttpServletRequest request,
                             HttpServletResponse response){
        EntityWrapper<HuLabor> entityWrapper = new EntityWrapper<HuLabor>(entityClass);
        propertyPreFilterable.addQueryProperty("id");
        // 预处理
        QueryableConvertUtils.convertQueryValueToEntityValue(queryable, entityClass);
        SerializeFilter filter = propertyPreFilterable.constructFilter(entityClass);
        PageJson<HuLabor> pagejson = new PageJson<HuLabor>(huLaborService.selectPoorList());
        String content = JSON.toJSONString(pagejson, filter);
        StringUtils.printJson(response, content);
    }


    /**
     * 文件上传
     * @param request
     * @param response
     * @return
     */
    @RequestMapping(value="file",method = RequestMethod.POST)
    @ResponseBody
    public String upload(HttpServletRequest request,HttpServletResponse response) {
       // response.setContentType("text/plain");
        CommonsMultipartResolver multipartResolver = new CommonsMultipartResolver(
                request.getSession().getServletContext());

        Object  objects=request.getParameter("sex");
        String filePath="";
        Object  object=request.getParameter("file");
        if (multipartResolver.isMultipart(request)) { // 判断request是否有文件上传
            MultipartHttpServletRequest multiRequest = (MultipartHttpServletRequest) request;
            Iterator<String> ite = multiRequest.getFileNames();
            while (ite.hasNext()) {
                MultipartFile file = multiRequest.getFile(ite.next());
                try {
                    Attachment attachment = attachmentService.upload(request, file);
                    filePath= attachment.getFilepath();
                    continue;
                } catch (IOException e) {
                    continue;
                } catch (InvalidExtensionException e) {
                    continue;
                } catch (FileUploadBase.FileSizeLimitExceededException e) {
                    continue;
                } catch (FileNameLengthLimitExceededException e) {
                    continue;
                }
            }
        }
        return request.getContextPath()+filePath;
    }

/*    public static String upload(MultipartFile file, HttpServletRequest request) {
        String filePath = "";
        if (file != null && !file.isEmpty()) {
            String path = request.getSession().getServletContext().getRealPath(DEFAULT_IMAGE_PATH);
//			System.out.println(path);
            File dir = new File(path);
            if (!dir.exists()) {
                dir.mkdirs();
            }
            String originalFilename = file.getOriginalFilename();
            String filename = System.currentTimeMillis() + originalFilename.substring(originalFilename.lastIndexOf("."), originalFilename.length());
            File distFile = new File(path +'/'+ filename);
            // if (!distFile.exists()) {
            // try {
            // distFile.createNewFile();
            // } catch (IOException e) {
            // e.printStackTrace();
            // }
            // }
            try {
                // FileUtils.copyInputStreamToFile(file.getInputStream(),
                // distFile);
                // CompressImage cimg = new CompressImage();
                Thumbnails.of(file.getInputStream()).size(1024, 768).outputQuality(0.75).toFile(distFile);
                // cimg.compressPic(path,path,filename,rName);
                filePath = DEFAULT_IMAGE_PATH + filename;
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
        return filePath;
    }*/
}
